import json
import logging
from base.types import MarketMessage
from utils.exceptions import InvalidMessageFormat, MarketAuthError

logger = logging.getLogger(__name__)

class MarketSpi:
    """行情回调接口（对应原LSpi的行情部分）"""
    def __init__(self):
        self.task_queue = None  # 由API初始化时注入

    def start(self, data_queue):
        """子进程入口（增加线程状态日志）"""
        logger.info("启动行情SPI消息处理线程")
        self.task_queue = data_queue
        try:
            while True:
                data = self.task_queue.get()
                if data is None:
                    logger.info("收到终止信号，退出行情消息循环")
                    break
#                logger.debug(f"行情队列获取消息: {data[:100]}...")
                self._process_data(data)
        except Exception as e:
            logger.error(f"行情消息处理线程异常: {str(e)}")
        finally:
            logger.info("行情SPI消息处理线程已退出")

    def _process_data(self, raw_data: str):
        """处理行情数据（优化批量处理）"""
        try:
            # 支持批量消息解析
            messages = json.loads(raw_data)
            if not isinstance(messages, list):
                messages = [messages]

            logger.info(f"收到行情消息: {messages}")
            for msg in messages:
                msg_type = msg.get("msgType")
                msg_data = msg.get("data")

                if msg_type == "@connected":
                    self.on_connected()
                elif msg_type == "@disconnected":
                    self.on_disconnected()
                elif msg_type == 9001:  # 行情快照
                    self.on_market_data(MarketMessage(**msg_data))
                elif msg_type == 9888:  # 信号推送
                    self.on_signal(msg_data)    
                elif msg_type == 3003:  # 订阅确认
                    self.on_rsp_subsribe(msg_data.get("securityId", []))
                elif msg_type == 3001:  # 认证响应
                    self._handle_auth_response(msg)
                elif msg_type == 1000:  # 请求认证
                    self.on_ready(msg)
                else:
                    logger.warning(f"未知行情消息类型: {msg_type}")
        except json.JSONDecodeError:
            raise InvalidMessageFormat(raw_data)
        except Exception as e:
            logger.error(f"行情消息处理失败: {str(e)}")

    def _handle_auth_response(self, msg: dict):
        """处理行情登录响应"""
        logger.info(f"收到行情登录响应: {msg}")
        if msg.get("errorId") == 0:
            self.api.update_auth_status(True)
            self.on_login(True)  # 保持与交易通道相同的回调命名
        else:
            self.on_login(
                False,
                error_msg=msg.get("retMsg")
            )

    def on_connected(self):
        """连接建立回调"""
        logger.info("行情服务器连接已建立")

    def on_disconnected(self):
        """连接断开回调"""
        logger.info("行情服务器连接已断开")

    def on_error(self, error):
        """错误回调"""
        logger.error(f"行情服务器错误: {error}")

    def on_message(self, message):
        """消息回调"""
        logger.debug(f"收到行情服务器消息: {message}")

    def on_login(self, success, error_msg=None):
        """登录回调"""
        if not success:
            logger.error(f"行情服务器登录失败: {error_msg}")
            raise MarketAuthError(error_msg)
        else:
            logger.info("行情服务器登录成功")

    def on_market_data(self, data: MarketMessage):
        """行情数据推送"""
        try:
            # 尝试多种可能的字段名组合
            security_id = (
                getattr(data, 'securityId', None) or 
                getattr(data, 'SecurityID', None) or
                data.__dict__.get('securityid') or
                '未知代码'
            )
            
            # 输出必要字段
            logger.debug(f"行情数据 - 证券代码: {security_id}")
#            logger.debug(f"完整数据: {data.__dict__}")  # 调试用完整数据

        except Exception as e:
            logger.error(f"处理行情数据时发生异常: {str(e)}")
            
    def on_signal(self, data):
        """信号推送"""
        logger.debug(f"收到信号推送: {data}")

    def on_depth_market_data(self, depth_data):
        """深度行情数据回调"""
        logger.debug(f"收到深度行情数据: {depth_data}")

    def on_rsp_subsribe(self, symbols: list):
        """订阅确认响应"""
        logger.info(f"成功订阅品种: {', '.join(symbols)}")

    def OnMarketData(self, data: MarketMessage):
        """行情数据回调（保留旧接口名称，向后兼容）"""
        pass  # 默认空实现，由子类重写

    def on_ready(self, msg: dict):
        """请求认证回调"""
        logger.info(f"收到请求认证消息: {msg}")
